package com.hailiang.study.apache.commons.collections4;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Equator;
import org.junit.Test;

import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 比较两个集合是否相等
 */
public class CollectionUtils_isEqualCollection {

    /**
     * 基本类型，比较两个集合是否相等
     */
    @Test
    public void test_isEqualCollection_01() {
        List<String> list01 = new ArrayList<>();
        list01.add("a");
        list01.add("b");
        list01.add("c");

        List<String> list02 = new ArrayList<>();
        list02.add("c");
        list02.add("a");
        list02.add("b");

        List<String> list03 = new ArrayList<>();
        list03.add("c");
        list03.add("d");


        System.out.println(CollectionUtils.isEqualCollection(list01, list02));
        System.out.println(CollectionUtils.isEqualCollection(list02, list03));
    }


    /**
     * 复合类型，比较两个集合是否相等
     */
    @Test
    public void test_isEqualCollection_02() {

        List<User> userList01 = new ArrayList<>();
        userList01.add(new User(new BigInteger("1001"), "李四"));
        userList01.add(new User(new BigInteger("1002"), "张三"));

        List<User> userList02 = new ArrayList<>();
        userList02.add(new User(new BigInteger("1002"), "张三"));
        userList02.add(new User(new BigInteger("1001"), "李四"));


        List<User> userList03 = new ArrayList<>();
        userList03.add(new User(new BigInteger("1001"), "王五"));
        userList03.add(new User(new BigInteger("1002"), "赵六"));

        System.out.println(CollectionUtils.isEqualCollection(userList01, userList02));
        System.out.println(CollectionUtils.isEqualCollection(userList02, userList03));


        Equator compareUser = new Equator<User>() {
            @Override
            public boolean equate(User o1, User o2) {
                return o1.getId().longValue() == o2.getId().longValue();
            }

            @Override
            public int hash(User o) {
                return o.getId().hashCode();
            }
        };

        //判断两个对象是否相等，自定义compareUser比较（即用户ID相等，就认为两个对象相等）
        System.out.println(CollectionUtils.isEqualCollection(userList01, userList02, compareUser));
        System.out.println(CollectionUtils.isEqualCollection(userList02, userList03, compareUser));
    }


    public static class User {
        private BigInteger id;
        private String name;

        public User(BigInteger id, String name) {
            this.id = id;
            this.name = name;
        }

        public BigInteger getId() {
            return id;
        }

        public void setId(BigInteger id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
